//
//  SocialTagListViewController.m
//  ShowYork
//
//  Created by hxh on 2020/12/21.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "DynamicPostTopicListViewController.h"
#import "DynamicMainTopicCell.h"
#import "DynamicSubTopicCell.h"
#import "DynamicTopicSearchView.h"
#import "SocialMainTopicModel.h"
#import "SocialSubTopicModel.h"


@interface DynamicPostTopicListViewController ()<UITableViewDelegate,UITableViewDataSource,DynamicTopicSearchViewDelegate,DynamicMainTopicCellDelegate,DynamicSubTopicCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)DynamicTopicSearchView *searchView;
@property (nonatomic,strong)UITableView *leftTableView;
@property (nonatomic,strong)UITableView *rightTableViewView;
@property (nonatomic,strong)UITableView *resultTableView;
@property (nonatomic,assign)BOOL isSearch;

@property (nonatomic,copy)NSString *selectedTag;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSMutableArray *resultArray;

@property (nonatomic,strong)SocialMainTopicModel *currentTopicModel;

@property (nonatomic,copy)NSString *searchKey;

@property (nonatomic,strong)NSURLSessionTask *task;

@property (nonatomic,assign)NSInteger pageIndex;

@property (nonatomic,strong)UIView *statusBar;

@end

@implementation DynamicPostTopicListViewController


- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
  
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    self.statusBar.backgroundColor = [UIColor clearColor];
    
}

- (instancetype)initWithSelectedTag:(NSString *)selectedTag{
    if (self = [super init]) {
        self.selectedTag = selectedTag;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.pageIndex = 1;
    
    [self setUI];
    [self loadDataSource];
    // Do any additional setup after loading the view.
}
- (void)setUI{
    
    self.isHideNavBar = YES;
    
    self.view.backgroundColor = RGBA(248, 248, 248, 1);
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:[UIView new]];
    self.navigationItem.leftBarButtonItem = item;
    
    self.searchView = [[DynamicTopicSearchView alloc]init];
    self.searchView.backgroundColor = RGBA(248, 248, 248, 1);
    self.searchView.delegate = self;
    [self.view addSubview:self.searchView];
    
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
    }];
    
    self.leftTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.leftTableView.estimatedRowHeight = 100;
    self.leftTableView.estimatedSectionFooterHeight = .0f;
    self.leftTableView.estimatedSectionHeaderHeight = .0f;
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.separatorColor = [UIColor clearColor];
    [self.view addSubview:self.leftTableView];
    
    self.rightTableViewView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.rightTableViewView.estimatedRowHeight = 100;
    self.rightTableViewView.estimatedSectionFooterHeight = .0f;
    self.rightTableViewView.estimatedSectionHeaderHeight = .0f;
    self.rightTableViewView.delegate = self;
    self.rightTableViewView.dataSource = self;
    self.rightTableViewView.separatorColor = [UIColor clearColor];
    [self.view addSubview:self.rightTableViewView];
    
    self.resultTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.resultTableView.estimatedRowHeight = 100;
    self.resultTableView.estimatedSectionFooterHeight = .0f;
    self.resultTableView.estimatedSectionHeaderHeight = .0f;
    self.resultTableView.separatorColor = [UIColor clearColor];
    self.resultTableView.delegate = self;
    self.resultTableView.dataSource = self;
    self.resultTableView.hidden = YES;
    [self.view addSubview:self.resultTableView];
    
    
    CGFloat rate = 125/kScreenW;

    [self.leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom);
        make.left.bottom.equalTo(self.view);
        make.width.mas_equalTo(kScreenW * rate);
    }];
    [self.rightTableViewView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom);
        make.right.bottom.equalTo(self.view);
        make.left.equalTo(self.leftTableView.mas_right);
    }];
    [self.resultTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    self.resultTableView.backgroundColor = [UIColor whiteColor];
    self.leftTableView.backgroundColor = RGBA(248, 248, 248, 1);
    self.rightTableViewView.backgroundColor = [UIColor whiteColor];
    self.resultTableView.showsVerticalScrollIndicator = NO;
    self.resultTableView.showsHorizontalScrollIndicator = NO;
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.showsHorizontalScrollIndicator = NO;
    self.rightTableViewView.showsVerticalScrollIndicator = NO;
    self.rightTableViewView.showsHorizontalScrollIndicator = NO;
  

        
    
    self.searchView.placeholderLabel = self.selectedTag;
    __weak typeof(self)weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf loadSearchResultTagListSource];
    }];
    
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    footer.cl_height = 138.0f;
    
    self.resultTableView.mj_footer = footer;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    if (@available(iOS 13.0, *)) {
        self.statusBar = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame];
        [[UIApplication sharedApplication].keyWindow addSubview:self.statusBar];
    }
}

- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserTopicList];
    param[@"pageIndex"] = @1;
    param[@"pageSize"] = @9999;
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetUserTopicList) parames:param success:^(id responseObj) {
        self.dataArray = [SocialMainTopicModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        if (self.dataArray.count != 0) {
            self.currentTopicModel = self.dataArray.firstObject;
            self.currentTopicModel.isSelected = YES;
        }
        [self.leftTableView reloadData];
        [self.rightTableViewView reloadData];
    } failure:^(id error) {
       
    }];
}

- (void)loadSearchResultTagListSource{
    
    [self.task cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetTopicByName];
    param[@"pageIndex"] = @(self.pageIndex);
    param[@"pageSize"] = @9999;
    param[@"tagName"] = self.searchKey;
    self.task = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetTopicByName) parames:param success:^(id responseObj) {
        if (self.pageIndex == 1) {
            self.resultArray = [SocialSubTopicModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.resultArray addObjectsFromArray:[SocialSubTopicModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        self.resultTableView.mj_footer.hidden = self.resultArray.count == 0;
        if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            CGPoint point = [self.view convertPoint:self.resultTableView.mj_footer.frame.origin toView:window];
            if (point.y < window.frame.size.height) {
                [(MJRefreshAutoNormalFooter *)self.resultTableView.mj_footer setTitle:@" " forState:MJRefreshStateNoMoreData];
            }else{
                [(MJRefreshAutoNormalFooter *)self.resultTableView.mj_footer setTitle:@"没有更多了" forState:MJRefreshStateNoMoreData];
            }
            [self.resultTableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        [self.resultTableView reloadData];
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGRect keyboardBounds = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        self.leftTableView.contentInset = UIEdgeInsetsMake(self.leftTableView.contentInset.top, 0, keyboardBounds.size.height, 0);
        self.rightTableViewView.contentInset = UIEdgeInsetsMake(self.rightTableViewView.contentInset.top, 0, keyboardBounds.size.height, 0);
        self.resultTableView.contentInset = UIEdgeInsetsMake(self.resultTableView.contentInset.top, 0, keyboardBounds.size.height, 0);
    });
}
- (void)keyboardWillHide:(NSNotification *)notification
{
    self.leftTableView.contentInset = UIEdgeInsetsZero;
    self.rightTableViewView.contentInset = UIEdgeInsetsZero;
    self.resultTableView.contentInset = UIEdgeInsetsZero;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.isSearch) {
        return self.resultArray.count;
    }
    
    if (self.leftTableView == tableView) {
        return self.dataArray.count;
    }
    if (self.rightTableViewView == tableView) {
        if (self.currentTopicModel != nil) {
            return self.currentTopicModel.secondTopicList.count;
        }
        return 0;
    }
    
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.leftTableView == tableView) {
        DynamicMainTopicCell *cell = [DynamicMainTopicCell cellWithTableView:tableView];
        [cell setModel:self.dataArray[indexPath.row]];
        cell.delegate = self;
        return cell;
    }
    if (self.rightTableViewView == tableView) {
        DynamicSubTopicCell *cell = [DynamicSubTopicCell cellWithTableView:tableView];
        [cell setModel:self.currentTopicModel.secondTopicList[indexPath.row]];
        cell.deletate = self;
        return cell;
    }
    DynamicSubTopicCell *cell = [DynamicSubTopicCell cellWithTableView:tableView];
    [cell setModel:self.resultArray[indexPath.row]];
    cell.deletate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
#pragma mark - ReleaseMainTagCellDelegate

- (void)updateCurrentTopicListWithItemModel:(SocialMainTopicModel *)itemModel{
    if (![itemModel.topicId isEqualToNumber:self.currentTopicModel.topicId]) {
        self.currentTopicModel.isSelected = NO;
        itemModel.isSelected = YES;
    }
    self.currentTopicModel = itemModel;

    [self.leftTableView reloadData];
    [self.rightTableViewView reloadData];
}
#pragma mark - ReleaseSubTagCellDelegate
- (void)selectedSubTopicItemModel:(SocialSubTopicModel *)subItemModel{
    if (self.selectedCurrentTagItem) {
        self.selectedCurrentTagItem(subItemModel);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - SocialTagSearchViewDelegate
/// 实时监听文字变化
- (void)textChange:(NSString *)text{
    
    if ([text isSpaceString] && text.length != 0) {
        return;
    }
    self.pageIndex = 1;
    self.searchKey = text;
    
    if (text.length == 0) {
        self.isSearch = NO;
        self.resultTableView.hidden = YES;
    }else{
        [self loadSearchResultTagListSource];
        self.isSearch = YES;
        self.resultTableView.hidden = NO;
        [self.resultTableView reloadData];
    }
    
}
/// 点击键盘的搜索栏
- (void)textSearch:(NSString *)text{
    
    if ([text isSpaceString] && text.length != 0) {
        return;
    }
    
    self.pageIndex = 1;
    self.searchKey = text;
    [self loadSearchResultTagListSource];
    
    self.isSearch = YES;
    self.resultTableView.hidden = NO;
    [self.resultTableView reloadData];
}
/// 视图开始编辑
- (void)textFieldBeginEditing{
    
}
/// 移除当前控制前
- (void)removeCurrentViewController{
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
